package com.chainyoung.component_tmperson.ui.activity.hdwallet;

import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.ui.mvp.contract.HdWalletSettingContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.HdWalletSettingPresenter;
import com.chainyoung.component_tmperson.ui.view.InputDialog;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.event.BaseEvent.EventCode.REFRESH_WALLET_NAME;

/**
 * 本地钱包设置/导出
 */
public class HdWalletSettingActivity extends BaseActivity<HdWalletSettingPresenter> implements HdWalletSettingContract.View {


    @BindView(R2.id.tv_name)
    TextView tvName;

    @BindView(R2.id.tv_backup_words)
    TextView tvBackUpWords;
    @BindView(R2.id.view1)
    View view1;
    @BindView(R2.id.sw_main)
    Switch swMain;


    private HdWalletCache hdWalletCache;

    private boolean isBackedUpWallet;

    private List<HdWalletCache> hdWalletCaches = new ArrayList<>();


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        setCurrentTitle("钱包设置");
        hdWalletCache = (HdWalletCache) getIntent().getSerializableExtra("hdwallet");
        if (hdWalletCache != null) {
            tvBackUpWords.setVisibility(TextUtils.isEmpty(hdWalletCache.getMnemonic()) ? View.GONE : View.VISIBLE);
            view1.setVisibility(TextUtils.isEmpty(hdWalletCache.getMnemonic()) ? View.GONE : View.VISIBLE);
            tvName.setText(hdWalletCache.getWalletName());
        }
        //isBackedUpWallet = SPUtil.getBoolean(LibConstant.BACKE_UP_MNEMONIC, false);
        isBackedUpWallet = SPUtil.getBoolean(hdWalletCache.getAddress(), false);
        tvBackUpWords.setText(isBackedUpWallet ? R.string.tmperson_check_words : R.string.tmperson_back_up_words);
        //tvSetMainWallet.setCompoundDrawablesRelativeWithIntrinsicBounds(hdWalletCache.isMainWallet()?R.mipmap.icon_unselect:R.mipmap.icon_selected,0,0,0);

        swMain.setChecked(hdWalletCache.isMainWallet());
        swMain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    hdWalletCache.setMainWallet(true);
                    updateWallet();
                    updateOtherWallets(false);
                } else {
                    hdWalletCache.setMainWallet(false);
                    updateWallet();
                    updateOtherWallets(true);
                }
            }
        });
    }

    @Override
    protected void initData() {
        getAllHdWallets();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_hdwallet_setting;
    }


    @OnClick(R2.id.ll_name)
    void setWalletName() {
        showInputNameDialog();
    }

    private InputDialog inputNameDialog;

    private void showInputNameDialog() {
        if (inputNameDialog == null) {
            inputNameDialog = new InputDialog(mContext, "请输入钱包名称", "", InputType.TYPE_CLASS_TEXT);
        }
        inputNameDialog.setEtContent(StringUtil.viewGetText(tvName));
        inputNameDialog.setMaxEditLength(10);
        inputNameDialog.setOnConfimrListener(new InputDialog.onConfimrListener() {
            @Override
            public void onConfirmListener(String content) {
                tvName.setText(content);
                hdWalletCache.setWalletName(content);
                updateWallet();
                inputNameDialog.close();
            }
        });
        inputNameDialog.show();
    }


    private InputDialog inputCodeDialog;

    @OnClick(R2.id.tv_backup_words)
    void backUpWords() {
        if (TextUtils.isEmpty(SPUtil.getString(LibConstant.PIN_CODE))) {
            lookUpWords();
            return;
        }
        long lastInputCodeTime = mAppComponent.appManager().getLastPinCodeTime();
        if (lastInputCodeTime == 0) {
            showInputCodeDialog(0);
        } else if (System.currentTimeMillis() - lastInputCodeTime > (300 * 1000)) {
            showInputCodeDialog(0);
        } else {
            //查看或者备份
            lookUpWords();
        }
    }

    private void lookUpWords() {
        if (isBackedUpWallet) {
            //查看助记词
            Intent intent = new Intent(mContext, WordsActivity.class);
            intent.putExtra("isFirst", false);
            intent.putExtra("hdwallet", hdWalletCache);
            mContext.startActivity(intent);
        } else {
            //备份助记词
            Intent intent = new Intent(mContext, PrepareBackUpWordsActivity.class);
            intent.putExtra("hdwallet", hdWalletCache);
            mContext.startActivity(intent);
        }
    }

    private void showInputCodeDialog(final int type) {

        inputCodeDialog = new InputDialog(mContext, "请输入6位PIN码", "", InputType.TYPE_NUMBER_VARIATION_PASSWORD | InputType.TYPE_CLASS_NUMBER
        );

        //inputCodeDialog.setEtContent(StringUtil.viewGetText(tvName));
        inputCodeDialog.setMaxEditLength(6);
        inputCodeDialog.setOnConfimrListener(new InputDialog.onConfimrListener() {
            @Override
            public void onConfirmListener(String content) {
                if (SPUtil.getString(LibConstant.PIN_CODE).equals(content)) {
                    mAppComponent.appManager().setLastPinCodeTime(System.currentTimeMillis());
                    if (type == 0) {
                        lookUpWords();
                    } else {
                        Intent intent = new Intent(mContext, HdWalletPrivateKeyActivity.class);
                        intent.putExtra("hdwallet", hdWalletCache);
                        mContext.startActivity(intent);
                    }
                    inputCodeDialog.close();
                } else {
                    ToastUtil.showToast("您输入的密码有误！");
                    return;
                }

            }
        });
        inputCodeDialog.show();
    }


    @OnClick(R2.id.tv_backup_privatekey)
    void backUpPrivateKey() {
        if (TextUtils.isEmpty(SPUtil.getString(LibConstant.PIN_CODE))) {
            Intent intent = new Intent(mContext, HdWalletPrivateKeyActivity.class);
            intent.putExtra("hdwallet", hdWalletCache);
            mContext.startActivity(intent);
            return;
        }
        long lastInputCodeTime = mAppComponent.appManager().getLastPinCodeTime();
        if (lastInputCodeTime == 0) {
            showInputCodeDialog(1);
        } else if (System.currentTimeMillis() - lastInputCodeTime > (300 * 1000)) {
            showInputCodeDialog(1);
        } else {
            //直接查看
            Intent intent = new Intent(mContext, HdWalletPrivateKeyActivity.class);
            intent.putExtra("hdwallet", hdWalletCache);
            mContext.startActivity(intent);
        }
    }


    private void updateWallet() {
        mPresenter.addHdWalletCache(hdWalletCache);
    }

    private void updateOtherWallets(boolean setOtherWalletMain) {
        if (setOtherWalletMain) {
            for (int i = 0; i < hdWalletCaches.size(); i++) {
                if (i == 0) {
                    HdWalletCache hdWalletCache1 = hdWalletCaches.get(0);
                    hdWalletCache1.setMainWallet(true);
                    mPresenter.addHdWalletCache(hdWalletCache1);
                } else if (hdWalletCaches.get(i).isMainWallet()) {
                    HdWalletCache hdWalletCache2 = hdWalletCaches.get(i);
                    hdWalletCache2.setMainWallet(false);
                    mPresenter.addHdWalletCache(hdWalletCache2);
                }
            }
        } else {
            for (int i = 0; i < hdWalletCaches.size(); i++) {
                HdWalletCache hdWalletCache3 = hdWalletCaches.get(i);
                if (hdWalletCache3.isMainWallet() && !hdWalletCache3.getAddress().equals(hdWalletCache.getAddress())) {
                    hdWalletCache3.setMainWallet(false);
                    mPresenter.addHdWalletCache(hdWalletCache3);
                }
            }
        }
    }


    @Override
    public void onAddHdWalletCacheSuccess(HdWalletCache data) {
        if (data.getAddress().equals(hdWalletCache.getAddress())) {
            EventBus.getDefault().post(new BaseEvent<>(REFRESH_WALLET_NAME, hdWalletCache));
        }
    }

    private void getAllHdWallets() {
        mPresenter.getAllHdWalletCaches(hdWalletCache.getCoinType());
    }

    @Override
    public void onGetAllHdWalletCaches(List<HdWalletCache> datas) {
        hdWalletCaches.addAll(datas);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //isBackedUpWallet = SPUtil.getBoolean(LibConstant.BACKE_UP_MNEMONIC, false);
        isBackedUpWallet = SPUtil.getBoolean(hdWalletCache.getAddress(), false);
        tvBackUpWords.setText(isBackedUpWallet ? R.string.tmperson_check_words : R.string.tmperson_back_up_words);
    }
}
